package com.ksyun.ks3.services.handler;

import com.ksyun.ks3.exception.Ks3ClientException;
import com.ksyun.ks3.exception.Ks3ServiceException;
import com.ksyun.ks3.model.HttpHeaders;
import com.ksyun.ks3.model.PartETag;
import com.ksyun.ks3.model.result.UploadPartResult;
import com.ksyun.ks3.model.transfer.RequestProgressListener;
import com.ksyun.ks3.services.request.Ks3HttpRequest;
import com.ksyun.ks3.services.request.UploadPartRequest;
import com.ksyun.ks3.util.ResponseUtils;

import okhttp3.Headers;

public abstract class UploadPartResponseHandler extends Ks3HttpResponseHandler implements RequestProgressListener {

    public abstract void onFailure(UploadPartRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException);

    public abstract void onSuccess(UploadPartRequest request, UploadPartResult result);

    @Override
    public final void onSuccess(Ks3HttpRequest request, int statusCode, Headers responseHeaders, byte[] response) {
        UploadPartResult result = new UploadPartResult();
        result.setStatusCode(statusCode);
        result.setHeaders(ResponseUtils.parseResponseHeaders(responseHeaders));
        result.setPartETag(parse(responseHeaders));
        this.onSuccess((UploadPartRequest) request, result);
    }

    @Override
    public final void onFailure(Ks3HttpRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
        this.onFailure((UploadPartRequest) request, clientException, serviceException);
    }


    @Override
    public final void onStart() {
    }

    @Override
    public final void onFinish() {
    }

    @Override
    public final void onCancel() {
    }

    @Override
    public final void onProgress(long bytesWritten, long totalSize) {
        double progress =
                Double.valueOf(totalSize > 0 ? bytesWritten * 1.0D / totalSize * 100.0D : -1.0D);
        onTaskProgress(progress);
    }

    public abstract void onTaskProgress(double progress);

    private PartETag parse(Headers responseHeaders) {
        PartETag result = new PartETag();
        Headers headers = responseHeaders;
        for (int i = 0; i < headers.size(); i++) {
            if (headers.name(i).equals(HttpHeaders.ETag.toString())) {
                result.seteTag(headers.value(i));
            }
        }
        return result;
    }


}
